<?php

/**
 * Menashop
 *
 * LICENSE
 *
 * This source file is subject to the license that is bundled
 * with this project in the file LICENSE.txt
 *
 * @category   Zend
 * @package    SearchController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

/**
 * @category   Zend
 * @package    SearchController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 */
class Storefront_SearchController extends Zend_Controller_Action
{

    /**
     * The logger
     * @var Zend_Log
     */
    protected $_logger;

    /**
     * The language ID
     * @var integer
     */
    protected $_languageId;

    /**
     * The database model for category
     * @var Storefront_Model_Category
     */
    protected $_categoryModel;

    /**
     * The AJAX flag
     * @var boolean
     */
    protected $_isAjax;

    /**
     * Initialize the controller
     */
    public function init()
    {
        // Get logger
        $this->_logger = Zend_Registry::get('log');

        // Get language from locale
        $locale = Zend_Registry::get('Zend_Locale');
        $languageModel = new Storefront_Model_Language();
        $this->_languageId = $languageModel->findIdByShortCode($locale->getLanguage());
        $this->view->language = $locale->getLanguage();

        // Form for search
        $form = new Storefront_Model_FormSearch();
        $form->setAction('/' . $locale->getLanguage() . '/search');
        $this->view->formSearch = $form;

        $this->view->shopMode = Zend_Registry::get('config')->shopMode;

        // Check AJAX
        if ($this->getRequest()->isXmlHttpRequest()) {

            // If AJAX - turn of auto render
            $this->_helper->layout->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);
            $this->_isAjax = true;
        } else {

            // Get category tree
            $this->_categoryModel = new Storefront_Model_Category();
            $this->view->categoryTree = $this->_categoryModel->getTree($this->_languageId);

            // Get cart
            $cartModel = new Storefront_Model_Cart();
            $this->view->cartCount = $cartModel->count();

            // Get current url
            $this->view->currentUrl = str_replace($locale->getLanguage() . '/', '', $this->_request->getRequestUri());

            $this->view->shopName = Zend_Registry::get('config')->shopName;
            $this->view->shopTitle = Zend_Registry::get('config')->shopTitle;
            $this->view->shopCity = Zend_Registry::get('config')->shopCity;
        }
    }

    /**
     * Action for result of search
     */
    public function resultAction()
    {
        // Check phrase
        $phrase = $this->_request->getParam('phrase');
        if (!$this->view->formSearch->isValid(array('phrase' => $phrase))) {
            $this->view->errors = $this->view->formSearch->getErrors();
            $this->_forward('index', 'Index');
        } else {
            $this->view->searchPhrase = $phrase;
            $words = explode(' ', $phrase);

            // Process page number
            $page = $this->_request->getParam('page');
            if (!$page) {
                $page = 1;
            }
            $this->view->page = $page;

            // Initialize form for content
            $form = new Storefront_Model_FormFound();
            $form->setAction('/' . $this->view->language . '/search');
            $form->phrase->setValue($phrase);

            // Process row count
            $rowCount = $this->_request->getParam('rows');
            if (!$rowCount) {
                $rowCount = 10;
            }
            $this->view->rowCount = $rowCount;
            $form->rows->setValue($rowCount);

            // Process sort order
            $sort = $this->_request->getParam('sort');
            if (!$sort) {
                $sort = 'price';
            }
            $form->sort->setValue($sort);

            // Process sort direction from request
            $direction = $this->_request->getParam('direction');
            if (!$direction) {
                $direction = 'asc';
            }
            $form->direction->setValue($direction);

            // Add form to view
            $this->view->formFound = $form;

            // Get pagination URL without pagination
            $requestUrl = $this->_request->getRequestUri();
            $paginationUrl = substr($requestUrl, 0, strpos($requestUrl, "?"));
            $paginationUrl .= '?phrase=' . $phrase;
            $paginationUrl .= '&sort=' . $sort;
            $paginationUrl .= '&direction=' . $direction;
            $this->view->paginationUrl = $paginationUrl;

            // Find manufacturers in phrase
            $manufacturerIds = null;
            $manufacturerModel = new Storefront_Model_Manufacturer();
            foreach (array_keys($words) as $key) {
                $manufacturerIds = $manufacturerModel->findIdsByName($words[$key]);
                if ($manufacturerIds) {
                    unset($words[$key]);
                    break;
                }
            }

            // Find categories in phrase
            $categoryIds = null;
            foreach (array_keys($words) as $key) {
                $categoryIds = $this->_categoryModel->findIdsByName($words[$key]);
                if ($categoryIds) {
                    unset($words[$key]);
                    break;
                }
            }

            // Find MPN in phrase
            $productIds = null;
            $productModel = new Storefront_Model_Product();
            foreach (array_keys($words) as $key) {
                $productIds = $productModel->findIdsByMpn($words[$key]);
                if ($productIds) {
                    unset($words[$key]);
                    break;
                }
            }
            $phrase = implode(' ', $words);

            // Get page count
            $productsCount = $productModel->getSearchResultCount($phrase, $this->_languageId, $productIds, $manufacturerIds, $categoryIds);
            $this->view->productsCount = $productsCount;
            $this->view->pageCount = ceil($productsCount / $rowCount);

            // Get result for page
            $result = $productModel->getSearchResult($phrase, $this->_languageId, $productIds, $manufacturerIds, $categoryIds, $sort, $direction, $page, $rowCount);
            $this->view->products = $result;

            if ($this->_isAjax) {

                // Render only AJAX contnet
                echo $this->view->render('/search/_products.phtml');
            }
        }

        // Get time of execution
        $startTime = Zend_Registry::get('startTime');
        $totalTime = round(microtime(true) - $startTime, 3);
        $this->_logger->debug(__METHOD__." spent $totalTime s");
    }

}

